<template>
  <el-container class="full-height">
    <!-- 顶部标题和操作按钮 -->
    <el-header class="header">
      <h1>知识库管理</h1>
      <el-button type="primary" @click="showCreateDialog = true">创建知识库</el-button>
    </el-header>

    <el-container class="content-container">
      <!-- 左侧：知识库列表 -->
      <el-aside width="200px" class="aside">
        <el-input v-model="searchText" placeholder="搜索知识库" clearable />
        <el-menu>
          <el-menu-item
            v-for="kb in filteredKnowledgeBases"
            :key="kb.id"
            @click="selectKnowledgeBase(kb)"
          >
            {{ kb.kbName }}
          </el-menu-item>
        </el-menu>
      </el-aside>

      <!-- 右侧：知识库详情和操作 -->
      <el-main class="main-content">
        <el-card v-if="selectedKnowledgeBase">
          <h2>{{ selectedKnowledgeBase.name }}</h2>
          <p>{{ selectedKnowledgeBase.description }}</p>

          <!-- 文件上传 -->
          <el-upload
            action="/knowledgeBase/upload"
            :on-change="handleFileUpload"
            :auto-upload="false"
            multiple
            :file-list = "fileList"
          >
            <el-button type="primary">上传文件</el-button>
          </el-upload>
          <el-button type="primary" @click="uploadFiled">上传</el-button>
          <el-button type="primary" @click="deleteKB">删除知识库</el-button>

          <!-- 文件列表 -->
          <el-table :data="selectedKnowledgeBase.files" style="width: 100%">
            <el-table-column prop="fileName" label="文件名" />
            <el-table-column label="操作" width="120">
              <template #default="{ row }">
                <el-button type="danger" size="small" @click="deleteFile(row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 问答功能 -->
          <el-divider>问答功能</el-divider>
          <el-input v-model="question" placeholder="请输入您的问题" />
          <el-button type="primary" @click="askQuestion">提问</el-button>
          <div v-if="answer">
            <h3>回答：</h3>
            <p>{{ answer }}</p>
          </div>
        </el-card>
      </el-main>
    </el-container>

    <!-- 创建知识库弹窗 -->
    <el-dialog v-model="showCreateDialog" title="创建知识库" width="30%">
      <el-form :model="newKnowledgeBase">
        <el-form-item label="名称">
          <el-input v-model="newKnowledgeBase.kbName" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="newKnowledgeBase.description" type="textarea" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showCreateDialog = false">取消</el-button>
        <el-button type="primary" @click="handleCreateKnowledgeBase">创建</el-button>
      </template>
    </el-dialog>
  </el-container>
</template>
<script setup>
import { ref, computed, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { knowledgeAdd, getknowledges, knowledgeDel,getBykbIdFilesList,uploadFile } from '@/api/knowledge.js'; // 引入 API 函数

// 知识库列表
const knowledgeBases = ref([]);
const fileList = ref([]);


// 选中的知识库
const selectedKnowledgeBase = ref(
  {
    kbId: null,
    kbName: '',
    description: '',
    files: [], 
  }
);

// 创建知识库弹窗
const showCreateDialog = ref(false);
const newKnowledgeBase = ref({
  kbName: '',
  description: '',
});

// 文件上传
const selectedFile = ref(null);

// 问答功能
const question = ref('');
const answer = ref('');

// 搜索功能
const searchText = ref('');

// 过滤后的知识库列表
const filteredKnowledgeBases = computed(() => {

  console.log('knowledge是：',knowledgeBases.value);
  return knowledgeBases.value.filter((kb) =>
    kb && kb.kbName.toLowerCase().includes(searchText.value.toLowerCase())
  );
});

// 选择知识库
const selectKnowledgeBase = async (kb) => {
  selectedKnowledgeBase.value = kb;
  console.log('选中的知识库是：',selectedKnowledgeBase.value);
  try{
    const response = await getBykbIdFilesList(kb.kbId);
    selectedKnowledgeBase.value.files = response.data;
  }catch(error){
    console.error('获取知识库文件列表失败:', error);
  }
};

// 创建知识库
const handleCreateKnowledgeBase = async () => {
  try {
    // 调用 knowledgeAdd API
    const response = await knowledgeAdd(newKnowledgeBase.value);
    ElMessage.success('知识库创建成功！');

    // 关闭弹窗并重置表单
    showCreateDialog.value = false;
    newKnowledgeBase.value = { kbName: '', description: '' };
  } catch (error) {
    console.error('创建知识库失败:', error);
    ElMessage.error('创建知识库失败，请重试！');
  }
};
// 删除知识库
const deleteKB = async () =>{
  console.log('删除kb是：',selectedKnowledgeBase.value);
  try{
    const response = await knowledgeDel(selectedKnowledgeBase.value);
    ElMessage.success('知识库删除成功！');
    
  } catch (error) {
    console.error('删除知识库失败:', error);
    ElMessage.error('删除知识库失败，请重试！');
  }
}

// 处理文件上传
const handleFileUpload = (file,files) => {
  fileList.value = files;
  console.log("file"+fileList.value)
};

// 上传文件
const uploadFiled = async() => {
  if (fileList.value === null){
    ElMessage.warning("请先选择文件")
    return
  }
  
  console.log('上传文件是：',fileList.value);
  console.log('上传kb是：',selectedKnowledgeBase.value);
  const kb = selectedKnowledgeBase.value;
  const formData = new FormData();
  //将所有文件都添加进FormData
  fileList.value.forEach(file =>{
    console.log(file.name);
    formData.append("files",file.raw);
  });
  formData.append('bucketName', kb.kbName);
  formData.append('kbId', kb.kbId);
  
  try {
    const response = await uploadFile(formData);
    if(response.code !== 200){
      ElMessage.error(response.data.message);
    }
    if(response.data.failedCount>0){
      ElMessage.warning(
        '${response.data.successCount}个成功，${response.data.failedCount}个失败'      );
      console.log("失败文件：",response.data.failedFiles);
    }else{
      ElMessage.success("所有文件上传成功")
    }
    console.log('文件上传成功:', response);

    selectedKnowledgeBase.value.files.push({
      fileName: selectedFile.value.name,
      minioUrl: response.data.minioUrl,
    });
    selectedFile.value = null;
  } catch (error) {
    console.error('文件上传失败:', error);
    ElMessage.error('文件上传失败，请重试！');
  }
};

// 删除文件
const deleteFile = (file) => {
  selectedKnowledgeBase.value.files = selectedKnowledgeBase.value.files.filter(
    (f) => f.id !== file.id
  );
};




// 提问功能
const askQuestion = () => {
  // 调用 Ollama 大模型生成回答
  answer.value = `这是关于 "${question.value}" 的回答。`;
};

// 在组件挂载时加载知识库数据
onMounted(async () => {
  try {
    console.log('加载知识库数据');
    const response = await getknowledges(); // 调用后端 API
    knowledgeBases.value = response.data; // 将返回的数据赋值给 knowledgeBases
    console.log('返回的response是：',response.data);
  } catch (error) {
    console.error('加载知识库失败:', error);
    ElMessage.error('加载知识库失败，请重试！');
  }
});
</script>
<style scoped>
.full-height {
  height: 100vh; /* 使用视口高度 */
  display: flex;
  flex-direction: column;
}

.header {

  background-color: #409eff;
  color: white;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
  margin-top: 30px;
  height: 60px !important; /* 固定头部高度 */
}

.content-container {
  flex: 1; /* 占据剩余空间 */
  overflow: hidden; /* 防止内部内容溢出 */
}

.aside {
  background-color: #f5f7fa;
  border-right: 1px solid #e4e7ed;
  overflow-y: auto; /* 添加滚动条 */
}

.main-content {
  padding: 20px;
  overflow-y: auto; /* 添加滚动条 */
}

.el-card {
  margin-bottom: 20px;
}

.el-divider {
  margin: 20px 0;
}

.el-menu {
  border-right: none;
}

.el-menu-item {
  padding: 0 20px;
  height: 40px;
  line-height: 40px;
}

.el-menu-item:hover {
  background-color: #ecf5ff;
}

.el-upload {
  margin-bottom: 20px;
}
</style>